<?php
// +—————————————————————————————————————————————————————————————————————
// | Created by Yunbao
// +—————————————————————————————————————————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +—————————————————————————————————————————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +—————————————————————————————————————————————————————————————————————
// | Date: 2022-02-17
// +—————————————————————————————————————————————————————————————————————
	/* Redis链接 */
	function connectionRedis(){
		$REDIS_HOST= DI()->config->get('app.REDIS_HOST');
		$REDIS_AUTH= DI()->config->get('app.REDIS_AUTH');
		$REDIS_PORT= DI()->config->get('app.REDIS_PORT');
		$redis = new Redis();
		$redis -> pconnect($REDIS_HOST,$REDIS_PORT);
		$redis -> auth($REDIS_AUTH);

		return $redis;
	}
	/* 设置缓存 */
	function setcache($key,$info){
		$config=getConfigPri();
		if($config['cache_switch']!=1){
			return 1;
		}

		DI()->redis->set($key,json_encode($info));
		DI()->redis->expire($key, $config['cache_time']); 

		return 1;
	}	
	/* 设置缓存 可自定义时间*/
	function setcaches($key,$info,$time=0){
		DI()->redis->set($key,json_encode($info));
        if($time > 0){
            DI()->redis->expire($key, $time); 
        }
		
		return 1;
	}
	/* 获取缓存 */
	function getcache($key){
		$config=getConfigPri();

		if($config['cache_switch']!=1){
			$isexist=false;
		}else{
			$isexist=DI()->redis->Get($key);
		}

		return json_decode($isexist,true);
	}		
	/* 获取缓存 不判断后台设置 */
	function getcaches($key){

		$isexist=DI()->redis->Get($key);
		
		return json_decode($isexist,true);
	}
	
	/* 删除缓存 */
	function delcache($key){
		$isexist=DI()->redis->del($key);
		return 1;
	}	
    
    /* 密码检查 */
	function passcheck($user_pass) {
        /* 必须包含字母、数字 */
        $preg='/^(?=.*[A-Za-z])(?=.*[0-9])[a-zA-Z0-9~!@&%#_]{6,20}$/';
        $isok=preg_match($preg,$user_pass);
        if($isok){
            return 1;
        }
        return 0;
	}	
	/* 检验手机号 */
	function checkMobile($mobile){
		$ismobile = preg_match("/^1[3|4|5|6|7|8|9]\d{9}$/",$mobile);
		if($ismobile){
			return 1;
		}else{
			return 0;
		}
	}
	/* 随机数 */
	function random($length = 6 , $numeric = 0) {
		PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
		if($numeric) {
			$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
		} else {
			$hash = '';
			$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
			$max = strlen($chars) - 1;
			for($i = 0; $i < $length; $i++) {
				$hash .= $chars[mt_rand(0, $max)];
			}
		}
		return $hash;
	}


	function Post($curlPost,$url){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_NOBODY, true);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
		$return_str = curl_exec($curl);
		curl_close($curl);
		return $return_str;
	}
	
	function xml_to_array($xml){
		$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
		if(preg_match_all($reg, $xml, $matches)){
			$count = count($matches[0]);
			for($i = 0; $i < $count; $i++){
			$subxml= $matches[2][$i];
			$key = $matches[1][$i];
				if(preg_match( $reg, $subxml )){
					$arr[$key] = xml_to_array( $subxml );
				}else{
					$arr[$key] = $subxml;
				}
			}
		}
		return $arr;
	}


	/* 发送验证码*/
	function sendCode($mobile,$code){
        
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
        
		$config = getConfigPri();
        
        if(!$config['sendcode_switch']){
            $rs['code']=667;
			$rs['msg']='123456';
            return $rs;
        }

      

	
		$res=sendCodeByTencentSms($country_code,$mobile,$code);//腾讯云
		


		return $res;
	}

	

	//腾讯云短信
	function sendCodeByTencentSms($nationCode,$mobile,$code){
		require_once API_ROOT."/../sdk/tencentSms/index.php";
		$rs=array();
		$configpri = getConfigPri();
        
        $appid=$configpri['tencent_sms_appid'];
        $appkey=$configpri['tencent_sms_appkey'];


		$smsSign_dl = $configpri['tencent_sms_signName'];
        $templateId_dl=$configpri['tencent_sms_templateCode'];
	
        $smsSign = $smsSign_dl;
        $templateId = $templateId_dl;

       

	
		$sender = new \Qcloud\Sms\SmsSingleSender($appid,$appkey);

		$params = [$code]; //参数列表与腾讯云后台创建模板时加的参数列表保持一致
		$result = $sender->sendWithParam($nationCode, $mobile, $templateId, $params, $smsSign, "", "");  // 签名参数未提供或者为空时，会使用默认签名发送短信
				
		//file_put_contents(API_ROOT.'/../log/sendCode_tencent_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 result:'.json_encode($result)."\r\n",FILE_APPEND);
		$arr=json_decode($result,TRUE);

		if($arr['result']==0 && $arr['errmsg']=='OK'){
            //setSendcode(array('type'=>'1','account'=>$mobile,'content'=>"验证码:".$code."---国家区号:".$nationCode));
			$rs['code']=0;
		}else{
			$rs['code']=1002;
			$rs['msg']=$arr['errmsg'];
			// $rs['msg']='验证码发送失败';
		} 
		return $rs;		
				
	}
    
    /* curl get请求 */
    function curl_get($url){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查  
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);  // 从证书中检查SSL加密算法是否存在
		$return_str = curl_exec($curl);
		curl_close($curl);
		return $return_str;
	}
    
	/* 检测文件后缀 */
	function checkExt($filename){
		$config=array("jpg","png","jpeg");
		$ext   =   pathinfo(strip_tags($filename), PATHINFO_EXTENSION);
		 
		return empty($config) ? true : in_array(strtolower($ext), $config);
	}	    
	/* 密码加密 */
	function setPass($pass){
		$authcode='rCt52pF2cnnKNB3Hkp';
		$pass="###".md5(md5($authcode.$pass));
		return $pass;
	}	
    /* 去除NULL 判断空处理 主要针对字符串类型*/
	function checkNull($checkstr){
        $checkstr=trim($checkstr);
		$checkstr=urldecode($checkstr);
        if(get_magic_quotes_gpc()==0){
			$checkstr=addslashes($checkstr);
		}

		if( strstr($checkstr,'null') || (!$checkstr && $checkstr!=0 ) ){
			$str='';
		}else{
			$str=$checkstr;
		}

		$str=htmlspecialchars($str);
		return $str;	
	}
	/* 去除emoji表情 */
	function filterEmoji($str){
		$str = preg_replace_callback(
			'/./u',
			function (array $match) {
				return strlen($match[0]) >= 4 ? '' : $match[0];
			},
			$str);
		return $str;
	}	
	/* 公共配置 */
	function getConfigPub() {
		$key='getConfigPub';
		$config=getcaches($key);
		$config=false;
		if(!$config){
			$config= DI()->notorm->option
					->select('option_value')
					->where("option_name='site_info'")
					->fetchOne();

            $config=json_decode($config['option_value'],true);
            
            if($config){
                setcaches($key,$config);
            }
			
		}
        if(isset($config['live_time_coin'])){
            if(is_array($config['live_time_coin'])){
                
            }else if($config['live_time_coin']){
                $config['live_time_coin']=preg_split('/,|，/',$config['live_time_coin']);
            }else{
                $config['live_time_coin']=array();
            }
        }else{
            $config['live_time_coin']=array();
        }
        
        if(isset($config['login_type'])){
            if(is_array($config['login_type'])){
                
            }else if($config['login_type']){
                $config['login_type']=preg_split('/,|，/',$config['login_type']);
            }else{
                $config['login_type']=array();
            }
        }else{
            $config['login_type']=array();
        }
        

        
        if(isset($config['live_type'])){
            if(is_array($config['live_type'])){
                
            }else if($config['live_type']){
                $live_type=preg_split('/,|，/',$config['live_type']);
                foreach($live_type as $k=>$v){
                    $live_type[$k]=preg_split('/;|；/',$v);
                }
                $config['live_type']=$live_type;
            }else{
                $config['live_type']=array();
            }
        }else{
            $config['live_type']=array();
        }
        
		return 	$config;
	}		
	
	/* 私密配置 */
	function getConfigPri() {
		$key='getConfigPri';
		$config=getcaches($key);
		if(!$config){
			$config= DI()->notorm->option
					->select('option_value')
					->where("option_name='configpri'")
					->fetchOne();
            $config=json_decode($config['option_value'],true);
            if($config){
                setcaches($key,$config);
            }
			
		}


        
		return 	$config;
	}		
	
	/**
	 * 返回带协议的域名
	 */
	function get_host(){
		$config=getConfigPub();
		return $config['site'];
	}	
	
	/**
	 * 转化数据库保存的文件路径，为可以访问的url
	 */
	function get_upload_path($file){
        if($file==''){
            return $file;
        }
		if(strpos($file,"http")===0){
			return html_entity_decode($file);
		}else if(strpos($file,"/")===0){
			$filepath= get_host().$file;
			return html_entity_decode($filepath);
		}else{

			$fileinfo=explode("_",$file);//上传云存储标识：qiniu：七牛云；aws：亚马逊

			$storage_type=$fileinfo[0];
			$start=strlen($storage_type)+1;

			if($storage_type=='qiniu'){ //七牛云

				$space_host= DI()->config->get('app.Qiniu.space_host');
				$file=substr($file,$start);
				$filepath=$space_host."/".$file;
	            return html_entity_decode($filepath);

			}else{

				$uptype=DI()->config->get('app.uptype');
	            if($uptype==1){
	                $space_host= DI()->config->get('app.Qiniu.space_host');
	                $filepath=$space_host."/".$file;
	            }else{
	                $filepath= get_host().'/upload/'.$file;
	            }

	            return html_entity_decode($filepath);

			}

            
			
			
		}
	}
	


	
	/* 判断权限 */
	function isAdmin($uid,$liveuid) {

		if($uid<0){
			return 30;
		}
		if($uid==$liveuid){
			return 50;
		}
		$isuper=isSuper($uid);
		if($isuper){
			return 60;
		}
		$isexist=DI()->notorm->live_manager
					->select("*")
					->where('uid=? and liveuid=?',$uid,$liveuid)
					->fetchOne();
		if($isexist){
			return  40;
		}
		
		return  30;
			
	}	

	/* 判断token */
	function checkToken($uid,$token) {
		$userinfo=getcaches("token_".$uid);
		if(!$userinfo){
			$userinfo=DI()->notorm->user_token
						->select('token,expire_time')
						->where('user_id = ?', $uid)
						->fetchOne();
            if($userinfo){
                setcaches("token_".$uid,$userinfo);
            }
			
		}

		if(!$userinfo || $userinfo['token']!=$token || $userinfo['expire_time']<time()){

			return 700;				
		}
        

        
        return 	0;				
				
	}	
	
	/* 用户基本信息 */
	function getUserInfo($uid,$type=0) {

		if($uid==0){
			if($uid==='goodsorder_admin'){

				$configpub=getConfigPub(); 

				$info['user_nicename']="订单消息";	
				$info['avatar']=get_upload_path('/orderMsg.png');
				$info['avatar_thumb']=get_upload_path('/orderMsg.png');
				$info['id']="goodsorder_admin";

			}

			$info['coin']="0";
			$info['sex']="1";
			$info['signature']='';
			$info['province']='';
			$info['city']='城市未填写';
			$info['birthday']='';
			$info['issuper']="0";
			$info['votestotal']="0";
			$info['consumption']="0";
			$info['location']='';
			$info['user_status']='1';

		}else{

			$info=getcaches("userinfo_".$uid);
			if($uid>0){
				$info=false;
			}
			
			
			if(!$info){
				$info=DI()->notorm->user
						->select('id,user_nicename,avatar,avatar_thumb,sex,signature,consumption,votestotal,province,city,birthday,user_status,location')
						->where('id=? and user_type="2"',$uid)
						->fetchOne();	
				if($info){
					
				}else if($type==1){
	                return 	$info;
	                
	            }else{
	                $info['id']=$uid;
	                $info['user_nicename']='用户不存在';
	                $info['avatar']='/default.jpg';
	                $info['avatar_thumb']='/default_thumb.jpg';
	                $info['sex']='0';
	                $info['signature']='';
	                $info['consumption']='0';
	                $info['votestotal']='0';
	                $info['province']='';
	                $info['city']='';
	                $info['birthday']='';
	                $info['issuper']='0';
	                $info['user_status']='1';
	                $info['location']='';
	            }

	            if($uid<0){
	            	$info['user_nicename']='游客';
	            }


	            if($info){
	                setcaches("userinfo_".$uid,$info);
	            }
				
			}
	        if($info){
	            $info['level']=getLevel($info['consumption']);
	            $info['level_anchor']=getLevelAnchor($info['votestotal']);
	            $info['avatar']=get_upload_path($info['avatar']);
	            $info['avatar_thumb']=get_upload_path($info['avatar_thumb']);

	            if($info['birthday']){
	                $info['birthday']=date('Y-m-d',$info['birthday']);   
	            }else{
	                $info['birthday']='';
	            }
	            
	        }


		}

		
		return 	$info;		
	}
	
	/* 会员等级 */
	function getLevelList(){
        $key='level';
		$level=getcaches($key);
		if(!$level){
			$level=DI()->notorm->level
					->select("*")
					->order("level_up asc")
					->fetchAll();
            if($level){
                setcaches($key,$level);	
            }
					 
		}
        
        foreach($level as $k=>$v){
            $v['thumb']=get_upload_path($v['thumb']);
            $v['thumb_mark']=get_upload_path($v['thumb_mark']);
            $v['bg']=get_upload_path($v['bg']);
            if($v['colour']){
                $v['colour']='#'.$v['colour'];
            }else{
                $v['colour']='#ffdd00';
            }
            $level[$k]=$v;
        }
        
        return $level;
    }
	function getLevel($experience){
		$levelid=1;
        $level_a=1;
		$level=getLevelList();

		foreach($level as $k=>$v){
			if( $v['level_up']>=$experience){
				$levelid=$v['levelid'];
				break;
			}else{
				$level_a = $v['levelid'];
			}
		}
		$levelid = $levelid < $level_a ? $level_a:$levelid;
		return (string)$levelid;
	}
	/* 主播等级 */
	function getLevelAnchorList(){
		$key='levelanchor';
		$level=getcaches($key);
		if(!$level){
			$level=DI()->notorm->level_anchor
					->select("*")
					->order("level_up asc")
					->fetchAll();
            if($level){
                setcaches($key,$level);
            }
            
		}
        
        foreach($level as $k=>$v){
            $v['thumb']=get_upload_path($v['thumb']);
            $v['thumb_mark']=get_upload_path($v['thumb_mark']);
            $v['bg']=get_upload_path($v['bg']);
            $level[$k]=$v;
        }
        
        return $level;
    }
	function getLevelAnchor($experience){
		$levelid=1;
		$level_a=1;
        $level=getLevelAnchorList();

		foreach($level as $k=>$v){
			if( $v['level_up']>=$experience){
				$levelid=$v['levelid'];
				break;
			}else{
				$level_a = $v['levelid'];
			}
		}
		$levelid = $levelid < $level_a ? $level_a:$levelid;
		return (string)$levelid;
	}

	/* 统计 直播 */
	function getLives($uid) {
		/* 直播中 */
		$count1=DI()->notorm->live
				->where('uid=? and islive="1"',$uid)
				->count();
		/* 回放 */
		$count2=DI()->notorm->live_record
					->where('uid=? ',$uid)
					->count();
		return 	$count1+$count2;
	}		
	
	/* 统计 关注 */
	function getFollows($uid) {
		$count=DI()->notorm->user_attention
				->where('uid=? ',$uid)
				->count();
		return 	$count;
	}			
	
	/* 统计 粉丝 */
	function getFans($uid) {
		$count=DI()->notorm->user_attention
				->where('touid=? ',$uid)
				->count();
		return 	$count;
	}		
	/**
	*  @desc 根据两点间的经纬度计算距离
	*  @param float $lat 纬度值
	*  @param float $lng 经度值
	*/
	function getDistance($lat1, $lng1, $lat2, $lng2){
		$earthRadius = 6371000; //近似地球半径 单位 米
		 /*
		   Convert these degrees to radians
		   to work with the formula
		 */

		$lat1 = ($lat1 * pi() ) / 180;
		$lng1 = ($lng1 * pi() ) / 180;

		$lat2 = ($lat2 * pi() ) / 180;
		$lng2 = ($lng2 * pi() ) / 180;


		$calcLongitude = $lng2 - $lng1;
		$calcLatitude = $lat2 - $lat1;
		$stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);  $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
		$calculatedDistance = $earthRadius * $stepTwo;
		
		$distance=$calculatedDistance/1000;
		if($distance<10){
			$rs=round($distance,2);
		}else if($distance > 1000){
			$rs='1000';
		}else{
			$rs=round($distance);
		}
		return $rs.'km';
	}
	/* 判断账号是否禁用 */
	function isBanBF($uid){
		$status=DI()->notorm->user
					->select("user_status")
					->where('id=?',$uid)
					->fetchOne();
		if(!$status || $status['user_status']==0){
			return '0';
		}
		return '1';
	}
	/* 是否认证 */
	function isAuth($uid){
		$status=DI()->notorm->user_auth
					->select("status")
					->where('uid=?',$uid)
					->fetchOne();
		if($status && $status['status']==1){
			return '1';
		}

		return '0';
	}
	/* 过滤字符 */
	function filterField($field){
		$configpri=getConfigPri();
		
		$sensitive_field=$configpri['sensitive_field'];
		
		$sensitive=explode(",",$sensitive_field);
		$replace=array();
		$preg=array();
		foreach($sensitive as $k=>$v){
			if($v!=''){
				$re='';
				$num=mb_strlen($v);
				for($i=0;$i<$num;$i++){
					$re.='*';
				}
				$replace[$k]=$re;
				$preg[$k]='/'.$v.'/';
			}else{
				unset($sensitive[$k]);
			}
		}
		
		return preg_replace($preg,$replace,$field);
	}
	/* 时间差计算 */
	function datetime($time){
		$cha=time()-$time;
		$iz=floor($cha/60);
		$hz=floor($iz/60);
		$dz=floor($hz/24);
		/* 秒 */
		$s=$cha%60;
		/* 分 */
		$i=floor($iz%60);
		/* 时 */
		$h=floor($hz/24);
		/* 天 */
		
		if($cha<60){
			return $cha.'秒前';
		}else if($iz<60){
			return $iz.'分钟前';
		}else if($hz<24){
			return $hz.'小时'.$i.'分钟前';
		}else if($dz<30){
			return $dz.'天前';
		}else{
			return date("Y-m-d",$time);
		}
	}		


	/* 时长格式化 */
	function getSeconds($time,$type=0){

			if(!$time){
				return (string)$time;
			}

		    $value = array(
		      "years"   => 0,
		      "days"    => 0,
		      "hours"   => 0,
		      "minutes" => 0,
		      "seconds" => 0
		    );
		    
		    if($time >= 31556926){
		      $value["years"] = floor($time/31556926);
		      $time = ($time%31556926);
		    }
		    if($time >= 86400){
		      $value["days"] = floor($time/86400);
		      $time = ($time%86400);
		    }
		    if($time >= 3600){
		      $value["hours"] = floor($time/3600);
		      $time = ($time%3600);
		    }
		    if($time >= 60){
		      $value["minutes"] = floor($time/60);
		      $time = ($time%60);
		    }
		    $value["seconds"] = floor($time);

		    if($value['years']){
		    	if($type==1&&$value['years']<10){
		    		$value['years']='0'.$value['years'];
		    	}
		    }

		    if($value['days']){
		    	if($type==1&&$value['days']<10){
		    		$value['days']='0'.$value['days'];
		    	}
		    }

		    if($value['hours']){
		    	if($type==1&&$value['hours']<10){
		    		$value['hours']='0'.$value['hours'];
		    	}
		    }

		    if($value['minutes']){
		    	if($type==1&&$value['minutes']<10){
		    		$value['minutes']='0'.$value['minutes'];
		    	}
		    }

		    if($value['seconds']){
		    	if($type==1&&$value['seconds']<10){
		    		$value['seconds']='0'.$value['seconds'];
		    	}
		    }

		    if($value['years']){
		    	$t=$value["years"] ."年".$value["days"] ."天". $value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
		    }else if($value['days']){
		    	$t=$value["days"] ."天". $value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
		    }else if($value['hours']){
		    	$t=$value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
		    }else if($value['minutes']){
		    	$t=$value["minutes"] ."分".$value["seconds"]."秒";
		    }else if($value['seconds']){
		    	$t=$value["seconds"]."秒";
		    }
		    
		    return $t;

	}

	/* 数字格式化 */
	function NumberFormat($num){
		if($num<10000){

		}else if($num<1000000){
			$num=round($num/10000,2).'万';
		}else if($num<100000000){
			$num=round($num/10000,1).'万';
		}else if($num<10000000000){
			$num=round($num/100000000,2).'亿';
		}else{
			$num=round($num/100000000,1).'亿';
		}
		return $num;
	}

	/**
	*  @desc 获取推拉流地址
	*  @param string $host 协议，如:http、rtmp
	*  @param string $stream 流名,如有则包含 .flv、.m3u8
	*  @param int $type 类型，0表示播流，1表示推流
	*/
	function PrivateKeyA($host,$stream,$type){

		$url=PrivateKey_tx($host,$stream,$type);

		
		return $url;
	}
	

	/**
	*  @desc 腾讯云推拉流地址
	*  @param string $host 协议，如:http、rtmp
	*  @param string $stream 流名,如有则包含 .flv、.m3u8
	*  @param int $type 类型，0表示播流，1表示推流
	*/
	function PrivateKey_tx($host,$stream,$type){
		$configpri=getConfigPri();
		$bizid=$configpri['tx_bizid'];
		$push_url_key=$configpri['tx_push_key'];
		$play_url_key=$configpri['tx_play_key'];
		$push=$configpri['tx_push'];
		$pull=$configpri['tx_pull'];
		$stream_a=explode('.',$stream);
		
	
		$streamKey = $stream_a[0];
	
		
		//$live_code = $bizid . "_" .$streamKey;      	
		$live_code = $streamKey; 

		$now=time();     	
		$now_time = $now + 3*60*60;
		$txTime = dechex($now_time);

		$txSecret = md5($push_url_key . $live_code . $txTime);
		$safe_url = "?txSecret=" .$txSecret."&txTime=" .$txTime;

		$play_safe_url='';
		//后台开启了播流鉴权
		if($configpri['tx_play_key_switch']){
			//播流鉴权时间

			$play_auth_time=$now+(int)$configpri['tx_play_time'];
			$txPlayTime = dechex($play_auth_time);
			$txPlaySecret = md5($play_url_key . $live_code . $txPlayTime);
			$play_safe_url = "?txSecret=" .$txPlaySecret."&txTime=" .$txPlayTime;

		}

		if($type==1){
			//$push_url = "rtmp://" . $bizid . ".livepush2.myqcloud.com/live/" .  $live_code . "?bizid=" . $bizid . "&record=flv" .$safe_url;	可录像
			$url = "rtmp://{$push}/live/" . $live_code . $safe_url;	
		}else{
			$url = "http://{$pull}/live/" . $live_code . ".flv".$play_safe_url;
			//$url = "http://{$pull}/live/" . $live_code . ".".$ext.$play_safe_url;（废弃）
		}
		
		return $url;
	}








	
	/* ip限定 */
	function ip_limit(){
		$configpri=getConfigPri();
		if($configpri['iplimit_switch']==0){
			return 0;
		}
		$date = date("Ymd");
		$ip= ip2long($_SERVER["REMOTE_ADDR"]) ; 
		
		$isexist=DI()->notorm->getcode_limit_ip
				->select('ip,date,times')
				->where(' ip=? ',$ip) 
				->fetchOne();
		if(!$isexist){
			$data=array(
				"ip" => $ip,
				"date" => $date,
				"times" => 1,
			);
			$isexist=DI()->notorm->getcode_limit_ip->insert($data);
			return 0;
		}elseif($date == $isexist['date'] && $isexist['times'] >= $configpri['iplimit_times'] ){
			return 1;
		}else{
			if($date == $isexist['date']){
				$isexist=DI()->notorm->getcode_limit_ip
						->where(' ip=? ',$ip) 
						->update(array('times'=> new NotORM_Literal("times + 1 ")));
				return 0;
			}else{
				$isexist=DI()->notorm->getcode_limit_ip
						->where(' ip=? ',$ip) 
						->update(array('date'=> $date ,'times'=>1));
				return 0;
			}
		}	
	}	

    /* 检测用户是否存在 */
    function checkUser($where){
        if($where==''){
            return 0;
        }

        $isexist=DI()->notorm->user->where($where)->fetchOne();
        
        if($isexist){
            return 1;
        }
        
        return 0;
    }
    
    /* 直播分类 */
    function getLiveClass(){
        $key="getLiveClass";
		$list=getcaches($key);
		if(!$list){
            $list=DI()->notorm->live_class
					->select("*")
                    ->order("list_order asc,id desc")
					->fetchAll();
            if($list){
                setcaches($key,$list);
            }
			
		}
        
        foreach($list as $k=>$v){
            $v['thumb']=get_upload_path($v['thumb']);
            $list[$k]=$v;
        }
        return $list;        
        
    }
    /* 校验签名 */
    function checkSign($data,$sign){
        $key=DI()->config->get('app.sign_key');
        $str='';
        ksort($data);
        foreach($data as $k=>$v){
            $str.=$k.'='.$v.'&';
        }
        
        $str.=$key;
        $newsign=md5($str);
        //file_put_contents("33333.txt", $newsign);
        /*var_dump($newsign);
        die;*/
        if($sign==$newsign){
            return 1;
        }
        return 0;
    }




	/* 时长格式化 */
	function getBanSeconds($cha,$type=0){		 
		$iz=floor($cha/60);
		$hz=floor($iz/60);
		$dz=floor($hz/24);
		/* 秒 */
		$s=$cha%60;
		/* 分 */
		$i=floor($iz%60);
		/* 时 */
		$h=floor($hz/24);
		/* 天 */
        
        if($type==1){
            if($s<10){
                $s='0'.$s;
            }
            if($i<10){
                $i='0'.$i;
            }

            if($h<10){
                $h='0'.$h;
            }
            
            if($hz<10){
                $hz='0'.$hz;
            }
            return $hz.':'.$i.':'.$s; 
        }
        
		
		if($cha<60){
			return $cha.'秒';
		}else if($iz<60){
			return $iz.'分钟'.$s.'秒';
		}else if($hz<24){
			return $hz.'小时'.$i.'分钟';
		}else if($dz<30){
			return $dz.'天'.$h.'小时';
		}
	}	
	
	/* 过滤：敏感词 */
	function sensitiveField($field){
		if($field){
			$configpri=getConfigPri();
			
			$sensitive_words=$configpri['sensitive_words'];
			
			$sensitive=explode(",",$sensitive_words);
			$replace=array();
			$preg=array();
			
			foreach($sensitive as $k=>$v){
				if($v!=''){
					if(strstr($field, $v)!==false){
						return 1001;
					}
				}else{
					unset($sensitive[$k]);
				}
			}
		}
		return 1;
	}

	

    
    /* 处理直播信息 */
    function handleLive($v){
        
        $configpri=getConfigPri();
        
        $nums=DI()->redis->zCard('user_'.$v['stream']);
        $v['nums']=(string)$nums;
        
        $userinfo=getUserInfo($v['uid']);
        $v['avatar']=$userinfo['avatar'];
        $v['avatar_thumb']=$userinfo['avatar_thumb'];
        $v['user_nicename']=$userinfo['user_nicename'];
        $v['sex']=$userinfo['sex'];
        $v['level']=$userinfo['level'];
        $v['level_anchor']=$userinfo['level_anchor'];
        
        if(!$v['thumb']){
            $v['thumb']=$v['avatar'];
        }
        if($v['isvideo']==0 ){
            $v['pull']=PrivateKeyA('rtmp',$v['stream'],0);
        }
        
        if($v['type']==1){
            $v['type_val']='';
        }
		$v['thumb']=get_upload_path($v['thumb']);
 
        
        return $v;
    }



    /**
	 * 判断是否为合法的身份证号码
	 * @param $mobile
	 * @return int
	 */
	function isCreditNo($vStr){
		
		$vCity = array(
		  	'11','12','13','14','15','21','22',
		  	'23','31','32','33','34','35','36',
		  	'37','41','42','43','44','45','46',
		  	'50','51','52','53','54','61','62',
		  	'63','64','65','71','81','82','91'
		);
		
		if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)){
		 	return false;
		}

	 	if (!in_array(substr($vStr, 0, 2), $vCity)){
	 		return false;
	 	}
	 
	 	$vStr = preg_replace('/[xX]$/i', 'a', $vStr);
	 	$vLength = strlen($vStr);

	 	if($vLength == 18){
	  		$vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
	 	}else{
	  		$vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
	 	}

		if(date('Y-m-d', strtotime($vBirthday)) != $vBirthday){
		 	return false;
		}

	 	if ($vLength == 18) {
	  		$vSum = 0;
	  		for ($i = 17 ; $i >= 0 ; $i--) {
	   			$vSubStr = substr($vStr, 17 - $i, 1);
	   			$vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
	  		}
	  		if($vSum % 11 != 1){
	  			return false;
	  		}
	 	}

	 	return true;
	}







    /**
     *  post提交数据 
     * @param  string $url 请求Url
     * @param  array $datas 提交的数据 
     * @return url响应返回的html
     */
    function sendPost_KDN($url, $datas) {
        $temps = array();   
        foreach ($datas as $key => $value) {
            $temps[] = sprintf('%s=%s', $key, $value);      
        }   
        $post_data = implode('&', $temps);
        $url_info = parse_url($url);
        if(empty($url_info['port']))
        {
            $url_info['port']=80;   
        }
        $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
        $httpheader.= "Host:" . $url_info['host'] . "\r\n";
        $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
        $httpheader.= "Connection:close\r\n\r\n";
        $httpheader.= $post_data;
        $fd = fsockopen($url_info['host'], $url_info['port']);
        fwrite($fd, $httpheader);
        $gets = "";
        $headerFlag = true;
        while (!feof($fd)) {
            if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                break;
            }
        }
        while (!feof($fd)) {
            $gets.= fread($fd, 128);
        }
        fclose($fd);  
        
        return $gets;
    }

    function is_true($val, $return_null=false){
        $boolval = ( is_string($val) ? filter_var($val, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) : (bool) $val );
        return ( $boolval===null && !$return_null ? false : $boolval );
    }

  



    




	/* 时长格式化 */
	function secondsFormat($time){

		$now=time();
		$cha=$now-$time;

		if($cha<60){
			return '刚刚';
		}

		if($cha>=4*24*60*60){ //超过4天
			$now_year=date('Y',$now);
			$time_year=date('Y',$time);

			if($now_year==$time_year){
				return date("m月d日",$time);
			}else{
				return date("Y年m月d日",$time);
			}

		}else{

			$iz=floor($cha/60);
			$hz=floor($iz/60);
			$dz=floor($hz/24);

			if($dz>3){
				return '3天前';
			}else if($dz>2){
				return '2天前';
			}else if($dz>1){
				return '1天前';
			}

			if($hz>1){
				return $hz.'小时前';
			}

			return $iz.'分钟前';
			

		}

	}


	



	//获取播流地址
    function getPull($stream){
    	$pull='';
    	$live_info=DI()->notorm->live->where("stream=?",$stream)->fetchOne();
    	if($live_info['isvideo']==1){ //视频
    		$pull=$live_info['pull'];
    	}else{
    		$configpri=getConfigPri();
    		if($configpri['cdn_switch']==5){
    			$wyinfo=PrivateKeyA('rtmp',$stream,1);
				$pull=$wyinfo['ret']["rtmpPullUrl"];
    		}else{
    			$pull=PrivateKeyA('rtmp',$stream,0);
    		}
    	}

    	return $pull;
	}
    




	//检测姓名
	function checkUsername($username){
		$preg='/^(?=.*\d.*\b)/';
		$isok = preg_match($preg,$username);
		if($isok){
			return 1;
		}else{
			return 0;
		}
	}





    //验证数字是否整数/两位小数
    function checkNumber($num){

    	if(floor($num) ==$num){
    		return 1;
    	}

    	if (preg_match('/^[0-9]+(.[0-9]{1,2})$/', $num)) {
    		return 1;
    	}

    	return 0;
    }

	